package mongo

import (
	"errors"
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/model"
	"cgs-server/server/store"
	"go.mongodb.org/mongo-driver/bson"
)

type bim struct {
	db *helper.Mongo
}

func (b *bim) List(mdl *model.BimModel, user *model.User) ([]*model.BimModel, error) {
	filter := bson.M{}

	mdl.ResolveFilter(mdl, user, &filter)

	results := []*model.BimModel{}
	err := b.db.FindMany(server.BimModelCollectionName, filter, &results)
	if err != nil {
		return nil, err
	}
	return results, nil
}

func (b *bim) Delete(mdl *model.BimModel, user *model.User) error {
	filter := bson.M{
		"fileId": mdl.FileId,
	}
	mdl.ResolveFilter(mdl, user, &filter)

	_, err := b.db.DeleteOne(server.BimModelCollectionName, filter)
	return err
}

func (b *bim) Update(mdl *model.BimModel, user *model.User) error {
	filter := bson.M{
		"fileId": mdl.FileId,
	}
	mdl.ResolveFilter(mdl, user, &filter)
	
	set := bson.M{}
	if mdl.Name != "" {
		set["name"] = mdl.Name
	}
	if mdl.FileName != "" {
		set["fileName"] = mdl.FileName
	}
	if mdl.Type != "" {
		set["type"] = mdl.Type
	}
	if mdl.FileType != "" {
		set["fileType"] = mdl.FileType
	}
	if mdl.FileSize > 0 {
		set["fileSize"] = mdl.FileSize
	}
	if len(mdl.Thumbnail) > 0 {
		set["thumbnail"] = mdl.Thumbnail
	}
	if mdl.TranslateStatus != "" {
		set["translateStatus"] = mdl.TranslateStatus
	}
	if mdl.DatabagId != "" {
		set["databagId"] = mdl.DatabagId
	}
	
	mdl.ResolveUpdateCondition(mdl, user, &set)

	update := bson.M{
		"$set": set,
	}

	_, err := b.db.UpdateOne(server.BimModelCollectionName, filter, update)
	return err
}

func (b *bim) Get(mdl *model.BimModel, user *model.User) (*model.BimModel, error) {

	filter := bson.M{
		"fileId": mdl.FileId,
	}
	mdl.ResolveFilter(mdl, user, &filter)

	result := &model.BimModel{}
	find, err := b.db.FindOne(server.BimModelCollectionName, filter, result)
	if err != nil {
		return nil, err
	}
	if !find {
		return nil, errors.New("bim model not found")
	}

	return result, nil
}

func (b *bim) Save(mdl *model.BimModel, user *model.User) error {
	mdl.ResolveEntity(mdl, user)
	_, err := b.db.InsertOne(server.BimModelCollectionName, mdl)
	return err
}

func newBimStore(ds *datastore) store.BimStore {
	return &bim{
		db: ds.db,
	}
}

